<?php
namespace app\wxapp\controller;

use app\model\Theme; 
use app\model\Fans; 
use app\model\Userdata; 
use app\model\Lottery; 

class LtRes extends Base
{
    public function Lt_res()
    {
/**
 * Created by 易宣
 * Desc:抽奖接口
 * User: cbw
 * Date: 2020/11/28
 */

global $_P, $_G;
$response = modelShow(40000);
if (!$_G['ispost']){
    $response = modelShow(50000);
}else{
    $fans = $this->checkuser();
    $system=$_G['system'];
    $params = $_P;
    $themeid = isset($params['themeid'])?$params['themeid']:'';

    if (!$themeid || empty($fans) || empty($system)){
        $response = modelShow(40001);
    }else{
        $theme = Theme::getThemeById($themeid);
        $config =   Theme::getConfig($themeid);
        if (!$theme){
            $response = modelShow(40002);
        }else{
            if ($params['ac']=='RoundGetLtr'){
                $check = Lottery::checkUserLtNum($fans,$config,$themeid);//获取用户的积分和抽奖次数
                if (!$check['lt_counter']){//抽奖次数
                    $response = modelShow(40010);
                    wxapp_result(0, '',$response);
                }
                try {

                    $get_key = 0;
                    $get_lt = [];
                    $rand_key = rand(1,10000);
                    $new_ratiio = 0;
                    $sql = "SELECT * from " . tablename(t_lottery) ." WHERE themeid=" . $themeid.
                        " and ltt_qty > 0 order by ltt_ratiio asc";
                    $list = db_select($sql);
                    foreach ($list as $k => $val)
                    {
                        $new_ratiio += $val['ltt_ratiio'];
                        if ($k+1 == count($list)){
                            $get_lt = $val;
                            $get_key = $val['ltt_id'];
                        }else if ($rand_key<=$new_ratiio){
                            $get_lt = $val;
                            $get_key = $val['ltt_id'];
                            break;
                        }
                    }

                    //未中奖
                    $sql = "SELECT * from " . tablename(t_lottery) ." WHERE themeid=" . $themeid.
                        " and it_type=2 order by ltt_ratiio desc";
                    $list = db_find($sql);
                    $free_lt = $list;
                    $free_key = $list['ltt_id'];

                    //检查是否有必中奖未中，如果有，则为必中奖
                    $sql = "SELECT count(*) from " . tablename(t_lottery) ." WHERE themeid=" . $themeid.
                        " and ltt_qty > 0 and it_type=3 ";
                    $bizhong = (int)db_fetchcolumn($sql);
                    if ($bizhong>0){
                        $tiaojian = Lottery::getUserRecordSql($themeid,$fans['uid']);
                        $sql = "SELECT * from " . tablename(t_lottery) ." WHERE themeid=" . $themeid.
                            " and ltt_qty > 0 and it_type=3 " . $tiaojian . " order by ltt_ratiio asc limit 1";
                        $list = db_find($sql);
                        if (!empty($list)){
                            $get_lt = $list;
                            $get_key = $list['ltt_id'];
                        }
                    }

                    //检查当前用户中奖奖项是否已经中过
                    $has_flag = Lottery::checkUserHasRecordFlag($fans['uid'],$themeid,$get_lt['ltt_id']);
                    if (!$has_flag){
                        //没有中过并且属于正常奖项
                        //当前奖项的库存量
                        $ltt_qty =$get_lt['ltt_qty'];
                        $new_ltt_qty = $ltt_qty-1;
                        //更新奖项库存量
                        $lt_item = db_update(t_lottery,['ltt_qty'=>$new_ltt_qty],['ltt_id'=>$get_lt['ltt_id']]);
                    }else{
                        //本次获取中奖奖项用户已经中过 替换未中奖奖项
                        $get_lt = $free_lt;
                        $get_key = $free_key;
                    }

                    //获取当前奖项在数组中的第几位；
                    $sql = " SELECT ltt_id from " . tablename(t_lottery) ." WHERE themeid=" . $themeid.
                        " order by  sort desc ,ltt_ratiio asc";
                    $list = db_select($sql);
                    foreach ($list as $index=>$item){
                        if ($item['ltt_id']==$get_key){
                            $get_key=$index;
                            break;
                        }
                    }

                    //用户表 剩余抽检次数减 抽奖机会表加
                    $chance_num = $fans['lt_counter'];
                    $new_chance_num = $chance_num-1;
                    $res = Lottery::updateFansInfo($fans['uid'],['lt_counter'=>$new_chance_num]);

                    $insert_data = [
                        'uid'=>$fans['uid'],
                        'type'=>2,
                        'add_key'=>1,
                        'updated_at'=>date("Y-m-d H:i:s"),
                        'themeid'=>$themeid,
                        'op_num'=>-1,
                        'today'=>date("Y-m-d",time())
                    ];
                    //抽奖机会表
                    $result = Lottery::insertUserRecords($insert_data);
                    //中奖表插入记录
                    $record_data = [
                        'ltt_id'=>$get_lt['ltt_id'],
                        'uid'=>$fans['uid'],
                        'themeid'=>$themeid,
                        'receive_key'=>$get_lt['receive_key'],
                        'receive_todo_num'=>$get_lt['receive_todo_num'],
                        'receive_remain_num'=>$get_lt['receive_todo_num'],
                        'status'=>2
                    ];
                    $res = Lottery::insertLtRerord($record_data);
                    $lr_id = $res;
                    $lr_item = Lottery::getLastLtRecordInfoByUid($get_lt['receive_key'],$lr_id);

                    $get_lt['receive_remain_num']=$get_lt['receive_todo_num'];


                    $end_str = '';
                    if ($get_lt['receive_key']==2){
                        $end_str = '天';
                    }
                    if ($get_lt['receive_key']==3){
                        $end_str = '次';
                    }
                    if ($get_lt['receive_key']==4){
                        $end_str = '个';
                    }
                    $msg = getUserRecordKeyMsg($get_lt['receive_key']).$get_lt['receive_remain_num'].$end_str;
                    $get_lt['msglong']='此奖品还需要将小程序'.$msg.'才可领取此奖品';
                    $get_lt['tips']='苹果手机需将海报分享至朋友圈';
                    if ($get_lt['receive_remain_num']==0){
                        $get_lt['msg'] = '待兑换';
                    }
                    //获取未中奖提示语
                    $lose_tips = $config['lose_tips'];
                    //用户日志采集
                    if ($get_lt){
                        $log_msg = '抽中'.$get_lt['ltt_title'];
                        Userdata::addLog($themeid, $fans['uid'], 21, $log_msg);
                    }
                    $result = array(
                        'res'=>$get_lt,
                        'get_key'=>$get_key,
                        'iswechatgroup'=>$system['iswechatgroup'],
                        'remnant_num' => $new_chance_num,
                        'lr_item'=>$lr_item,
                        'lose_tips'=>$lose_tips
                    );

                    //获取群二维码
                    if ($system['iswechatgroup']==1){
                        $group_qr = Fans::getwechatgroup($system,$themeid,0,0);
                        $result['group_qr_img'] = $group_qr;
                        $result['wechatgrouptips'] = $config['wechatgrouptips'];
                    }else{
                        $result['group_qr_img'] = str_replace('/logo.jpg','/thumb.jpg',$get_lt['ltp_img']);
                        $result['wechatgrouptips'] = '';
                    }
                    $response = modelShow(200,'',$result);
                }catch (Exception $e){
                    logging_run('错误日志:RoundGetLtr[参数：'.json_encode($params).'-错误信息:'.$e->getMessage());
                }
            }
            if ($params['ac']=='GetOrUpdateGroupQr'){
                try {
                    $refresh = isset($_P['is_refresh'])?$_P['is_refresh']:0;
                    $group_qr = Fans::getwechatgroup($system,$themeid,0,$refresh);
                    if (!$group_qr || $group_qr=='没有可用的群二维码'){//
                        $response = modelShow(40050);
                        wxapp_result(0, '',$response);
                    }
                    $response = modelShow(200,'',['group_qr_img'=>$group_qr]);
                }catch (Exception $e){
                    logging_run('错误日志:GetOrUpdateGroupQr[参数：'.json_encode($params).'-错误信息:'.$e->getMessage());
                }
            }
            //更新加入群聊状态
            if ($params['ac']=='joinWechatGroup'){
                $data = ['join_wechat_group'=>'yes'];
                $res = Lottery::updateLtRecordByLrId($params['lr_id'],$data);
                $response = modelShow(200);
            }
            //获取领奖相关数据 只针对于邀请好友
            if ($params['ac']=='getLotteryOpInfo'){
                $res = Lottery::getLastLtRecordInfoByUid(3,$params['lr_id']);
                $res= $res[0];
                if (!empty($res)){
                $receive_remain_num = intval( $res['receive_remain_num']);//剩余操作次数
                $receive_todo_num = intval($res['receive_todo_num']);//剩余操作次数

                $tips = '领取此奖品还需邀请'.$receive_remain_num.'位好友访问';
                $headlimit=$receive_todo_num;
                if ($headlimit>0){
                    $sql = " SELECT * from " . tablename(t_fans) ." WHERE themeid=" . $themeid.
                        " and fromuid='" . $_G['member']['uid'] . "' order by  id asc limit " . $headlimit;
                    $friendlist = db_select($sql);
                }
                }
                $res_data = [
                    'receive_remain_num'=>$receive_remain_num,
                    'receive_todo_num'=>$receive_todo_num,
                    'tips'=>$tips,
                    'friendlist'=>$friendlist
                ];
                $response = modelShow(200,'',$res_data);
            }

            //获取更多礼品
            if ($params['ac']=='getMoreLottery'){
                $fenxiang = db_find(" SELECT * from " . tablename(t_lottery) ." WHERE themeid=" . $themeid.
                    " and it_type=4 and ltt_qty>0 and receive_todo_num>0 ");

                $zhuli = db_find(" SELECT * from " . tablename(t_lottery) ." WHERE themeid=" . $themeid.
                    " and it_type=5 and ltt_qty>0 and receive_todo_num>0 ");

                if (!empty($zhuli)){
                    $receive_todo_num = intval($zhuli['receive_todo_num']);//剩余操作次数
                    $headlimit=$receive_todo_num;
                    if ($headlimit>0){
                        $sql = " SELECT avatar from " . tablename(t_fans) ." WHERE themeid=" . $themeid.
                            " and fromuid='" . $_G['member']['uid'] . "' order by  id asc limit " . $headlimit;
                        $friendlist = db_select($sql);
                        for ($x=count($friendlist)+1; $x<=$receive_todo_num; $x++) {
                            $friendlist[$x-1]['avatar']="https://css2020.yixuan.net/2020css/lottery/lottery/1217i12.png";
                        }
                    }
                }
                $res_data = [
                    'fenxiangtips'=>str_replace('#NUM',$fenxiang['receive_todo_num'],$config['morelottery_fenxiang']),
                    'zhulitips'=>str_replace('#NUM',$zhuli['receive_todo_num'],$config['morelottery_zhuli']),
                    'receive_remain_num'=>$receive_todo_num - count($friendlist),
                    'receive_todo_num'=>$receive_todo_num,
                    'friendlist'=>array_chunk($friendlist,5),
                    'fenxiang'=>$fenxiang,
                    'zhuli'=>$zhuli
                ];
                $response = modelShow(200,'',$res_data);
            }
            //获取更多礼品
            if ($params['ac']=='getLotteryDetail') {

                //抽奖增加减少记录
                $user_lottery_flag_list = formatSelfPointsFlag(Lottery::getLotteryOpFlagByUid($themeid,$fans['uid'],20));
                //抽奖攻略

                //获得抽奖的总数
                $sql = "select sum(op_num) from ".tablename(t_lot_record)." where uid = " . $_G['member']['uid'] . " and themeid=$themeid and op_num>0 ";
                $lt_counter_now = (int)db_fetchcolumn($sql);

                $lottery_method_list = Lottery::getUserLotteryOpList($lt_counter_now,$fans,$themeid,$config);
                //抽奖攻略 抽奖机会上限以及提示语
                $lottery_tips = Lottery::getLotteryMaxAndTips($lt_counter_now,$config);
                $res_data = [
                    'user_lottery_flag_list'=>$user_lottery_flag_list,
                    'lottery_method_list'=>$lottery_method_list,
                    'lottery_tips'=>$lottery_tips
                ];
                $response = modelShow(200,'',$res_data);
            }
        }
    }
}
wxapp_result(0, '',$response);
}
}